<!--
 * @Descripttion: 送装技师任职考核管理表
 * @version:
 * @Author: lehaixia
 * @Date: 2021-07-21 14:47:39
 * @LastEditors: lehaixia
 * @LastEditTime: 2022-04-29 09:53:22
-->
<template>
  <div>
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" label-width="80px">
          <el-form-item prop="officeId" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeId"
              @selectChange="officeChangeHandle"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="经销商名称">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeId},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              must-pid
              :disabled="!formData.officeId"
              :parent-id="formData.officeId"
              :value.sync="formData.disCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="staffCode" label="职员编码">
            <el-input v-model="formData.staffCode" placeholder="请输入安装技师" clearable />
          </el-form-item>
          <el-form-item prop="staffName" label="安装技师">
            <el-input v-model="formData.staffName" placeholder="请输入安装技师" clearable />
          </el-form-item>
          <el-form-item prop="phone" label="联系电话">
            <el-input v-model="formData.phone" placeholder="联系电话" clearable />
          </el-form-item>
          <el-form-item prop="assessResult" label="任职考核">
            <el-select v-model="formData.assessResult" placeholder="请选择">
              <el-option v-for="(r,i) in assessList" :key="i" :value="r.dictCode" :label="r.dictName" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" :loading="loading" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="handleTemplateExport">下载模板</Button>
        <Button type="primary" @click="handleExport">导出</Button>
        <DialogUpload
          ref="import"
          :show-file-num="false"
          text="导入"
          title="导入"
          :exist-file-list="existFileList"
          :click-down="false"
          :on-change="onChangeHandle"
          :on-remove="removeFileHandle"
          :on-exceed="onExceed"
          :limit="1"
          @confirm="onConfirmHandle"
        ></DialogUpload>
      </div>
      <table-box
        ref="refTable"
        table-size="mini"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :table-height="400"
      >
        <el-table-column slot="before" type="index" label="序号" width="55"></el-table-column>
      </table-box>

      <!-- 导出 -->
      <export-files
        v-if="showExport"
        title="导出"
        :visible.sync="showExport"
        :config="exportConfig"
      />

      <!-- 下载模板 -->
      <export-files
        v-if="showTemplateExport"
        title="下载模板"
        :visible.sync="showTemplateExport"
        :config="exportTemplateConfig"
      />

      <!-- 导入日志 -->
      <import-log
        v-if="showImportLog"
        :visible.sync="showImportLog"
      />
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { deepCopy } from '@/utils/'
import { JsonToUrl } from '@/utils/params-format'
import ImportLog from './component/ImportLog'
import { ccDict } from '@/api/dataDict'
import DialogUpload from '@/components/Upload/DialogUpload'
import { technicianAssessmentImport } from '@/api/technicianAssessment'

export default {
  name: 'TechnicianAssessment',
  components: { ContentWrap, FormContainer, Button, SearchSelectPicker, ImportLog, DialogUpload },
  props: {},
  data() {
    return {
      formData: {
        officeId: '',
        disCode: '',
        phone: '',
        staffCode: '',
        staffName: '',
        assessResult: ''
      },
      loading: false,
      existFileList: [], //
      fileList: [], // 已导入的文件
      assessList: [],
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `/call-center/api/v1/installTec/installTechnicianList`,
        tabIndex: 1,
        hideFuncBar: true,
        pageSize: 20,
        sort: 'assessTime',
        order: 'desc',
        setting: [{
          prop: 'officeId',
          minWidth: 110,
          label: '办事处编码'
        }, {
          prop: 'officeName',
          minWidth: 140,
          label: '办事处'
        }, {
          prop: 'disCode',
          label: '经销商编码',
          minWidth: 110
        }, {
          prop: 'distName',
          width: 180,
          label: '经销商名称'
        },
        /* {
          prop: 'businessStatus',
          label: '经销商经营状态',
          minWidth: 140,
          propEnum: {
            appCode: 'call-center',
            domainCode: 'marketing',
            dictTypeCode: 'BUSINESS_STATUS'
          }
        },  */
        {
          prop: 'staffCode',
          label: '职员编码',
          minWidth: 140
        }, {
          prop: 'staffName',
          label: '安装技师',
          minWidth: 120
        }, {
          prop: 'phone',
          label: '联系电话',
          minWidth: 120
        }, {
          prop: 'createTime',
          label: '入职时间',
          minWidth: 150
        }, {
          prop: 'assessResult',
          label: '任职考核',
          minWidth: 120,
          propEnum: {
            domainCode: 'marketing',
            appCode: 'call-center',
            dictTypeCode: 'ASSESSMENT_RESULT'
          }
        }, {
          prop: 'assessTime',
          label: '考试时间',
          minWidth: 150
        }],
        btnList: []
      },
      showExport: false, // 导出弹出框标识
      exportConfig: [{
        code: 'technicianAssessment', // 导出编码，前段定义，同一个config中code不能重复
        name: '送装技师任职考核表', // 导出名称，如：商品导出，导出用户
        async: false, // 是否异步
        dataApi: `/call-center/api/v1/installTec/installTechnicianReport`, // 导出数据的接口地址
        queryField: 'id'// 指定行导出的字段名称
      }],
      showTemplateExport: false, // 导出弹出框标识
      exportTemplateConfig: [{
        code: 'template', // 导出编码，前段定义，同一个config中code不能重复
        name: '送装技师任职考核表', // 导出名称，如：商品导出，导出用户
        async: false, // 是否异步
        templateApi: `/call-center/api/v1/installTec/excel/down`, // 模板导出接口
        queryField: 'id'// 指定行导出的字段名称
      }],
      showImportLog: false // 导入错误信息弹出框标识
    }
  },
  created() {
    this.ccDict()
  },
  methods: {
    // 获取任职考核的数据字典
    ccDict() {
      ccDict('ASSESSMENT_RESULT').then(res => {
        this.assessList = res && res.data || []
      })
    },
    // 办事处变化
    officeChangeHandle() {
      this.$set(this.formData, 'disCode', '')
    },
    // 查询
    queryHandle(type) {
      this.loading = true
      this.$refs.form
        .validate()
        .then(() => {
          // FIXME:
          const params = deepCopy(this.formData)

          this.tableConfig.interfacePath = `/call-center/api/v1/installTec/installTechnicianList/${JsonToUrl(params)}`
          this.$nextTick(() => {
            this.$refs.refTable.initTableData()
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 刷新主表
    refreshTable(isInit) {
      if (this.$refs.refTable) {
        this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
      }
    },
    // 导出
    handleExport() {
      this.showExport = true
      const params = deepCopy(this.formData)

      const exportConfig = this.exportConfig[0]
      exportConfig.dataApi = `/call-center/api/v1/installTec/installTechnicianReport${JsonToUrl(params)}`

      this.$set(this.exportConfig, 0, exportConfig)
    },
    handleTemplateExport() {
      this.showTemplateExport = true
    },
    handleLog() {
      this.showImportLog = true
    },
    // 导入相关
    onChangeHandle(file, fileList) {
      this.fileList = fileList
    },
    removeFileHandle(file, fileList) {
      this.fileList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 超出最大上传个数
    onExceed() {
      this.$message.info('每次最多只能导入一个文件')
    },
    // 导入
    onConfirmHandle(fileList) {
      if (fileList.length > 0) {
        const formData = new FormData()
        formData.append('file', fileList[0].raw)
        // 导入提示
        const loading = this.$loading({
          lock: true,
          text: '导入中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        technicianAssessmentImport(formData).then(res => {
          this.fileList = []
          this.$refs.import.cancelAllHandle()
          if (res.data instanceof Array && res.data.length > 0) {
            this.showErrMsg(res)
            this.refreshTable()
          } else {
            this.$message.success('导入成功！')
            this.refreshTable()
          }
        }).catch(res => {
          this.showErrMsg(res)
        }).finally(() => {
          loading.close()
        })
      }
    },
    // 显示错误
    showErrMsg(res) {
      const html = (res.data || []).sort((e1, e2) => {
        return e1.rowNum - e2.rowNum
      }).map(e => {
        return `<div>第${e.rowNum}行: ${e.errorMsg}</div>`
      })

      this.$alert(`<div>${res.msg}</div><div>${html.join('')}</div>`, '错误', {
        dangerouslyUseHTMLString: true,
        type: 'error'
      })
    }
  }
}
</script>
<style lang='scss' scoped>
/* @import url(); 引入css类 */
 /deep/ .function-box {
   display: flex !important;
 }
</style>
